<template>
  <el-card>
    <div slot="header">
      <h3>批量修改主供信息</h3>
    </div>
    <div>
      <el-row>
        <el-form :model="formData" ref="formData" label-width="80px" inline>
          <el-row>
            <el-form-item label="销售城市" prop="saleCityUuid">
              <el-checkbox
                v-model="saleCity.isAllChecked"
                :indeterminate="saleCity.isIndeterminate"
                :disabled="isEmptyForSaleCityGroups()"
                @change="handleAllCheckedForSaleCity"
              >全选</el-checkbox
              >
            </el-form-item>
          </el-row>
          <el-row
            v-if="!isEmptyForSaleCityGroups()"
            class="city-list-wrap"
          >
            <el-form-item>
              <el-checkbox-group
                v-model="formData.saleCityUuids"
                @change="handleCheckedForSaleCity"
              >
                <el-checkbox
                  v-for="city in options.saleCity"
                  :label="city.value"
                  :key="city.value"
                >{{ city.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="供应商" prop="supplyUuid">
              <el-select
                v-model="formData.supplyUuid"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options.supplier"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleBatchModify"
                >批量修改</el-button
              >
              <el-button @click="handleBatchDelete"
                >批量删除</el-button
              >
            </el-form-item>
          </el-row>
        </el-form>
      </el-row>
      <el-row type="flex" justify="end">
        <el-button
          v-show="showBtn('高级关联')"
          type="text"
          size="large"
          icon="el-icon-link"
          @click="handleSeniorLinked"
        >高级关联</el-button
        >
        <el-button
          v-show="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleGoodsLinked"
        >关联商品</el-button
        >
        <el-button
          v-if="canOpeState"
          type="text"
          size="large"
          @click="handleSubmit"
        >提交</el-button
        >
        <el-button
          type="text"
          size="large"
          @click="$router.push({ name: 'maintainList' })"
        >返回</el-button
        >
      </el-row>
      <el-row class="launch-reason-wrap" type=flex>
        <h4>发起原因：</h4>
        <el-input
          type="textarea"
          :autosize="{ minRows: 1.1 }"
          placeholder="请输入发起原因"
          v-model="launchReason">
        </el-input>
      </el-row>
      <el-row class="format_table_wrap">
        <SkusTable
          :defaultMinWidth="120"
          :loading="tableInfo.loading"
          :columns="tableInfo.columns"
          :dataSource="tableInfo.list"
          :showTableIndex="true"
          @handleCancelSelect="handleDeleteTableRow"
        />
      </el-row>
      <FooterFields :footerFields="footerFields" />
    </div>
    <!-- 关联商品弹框组件 -->
    <AssociatedDialog
      :columns="goodsLinked.columns"
      :requestApi="goodsLinked.requestApi"
      :distinctParams="goodsLinked.distinctParams"
      :dimensionKeyList="goodsLinked.dimensionKeyList"
      @getRowList="getTableDataByGoodsLinked"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getTableDataBySeniorLinked"
    />
    <basic-dialog
      title="提交原因"
      :visible="submitReason.visible"
    >
      <el-row type="flex" justify="center">
        <h4 style="color: #E6A23C;">提交时将会自动删除没有修改过的数据</h4>
      </el-row>
      <el-row type="flex" justify="center">
        <el-input
          :rows="6"
          resize="none"
          type="textarea"
          maxlength="100"
          show-word-limit
          v-model="launchReason">
        </el-input>
      </el-row>
      <el-row slot="ft" type="flex" justify="center">
        <el-button
          type="primary"
          v-preventReClick
          :loading="btnLoading.submit"
          @click="handleSubmitBySubmitReason">确认</el-button
        >
        <el-button @click="handleCloseBySubmitReason">取消</el-button>
      </el-row>
    </basic-dialog>
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapState, mapGetters, mapMutations } from 'vuex';
import SkusTable from '@/components/skusTable';
import AssociatedDialog from './components/associatedDialog';
import { getBatchModifyColumnsFn } from './constants';
import BasicDialog from '@/components/BasicDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import FooterFields from '@/pages/commodity/components/FooterFields';
import { BATCH_EDIT_MAINSUPPLY } from '@/constants/exportAmountLimit';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
import { getArraysByMaps, getListByMapDimensionKey, getCanOpeState } from '@/utils/getUtils';
export default {
  components: {
    SkusTable,
    AssociatedDialog,
    BasicDialog,
    SeniorLinkedDialog,
    FooterFields
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      footerFields: {}, // 表尾字段
      launchReason: '', // 发起原因(原提交原因字段)
      seniorLinked: {
        visible: false,
        columns: [{
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{ skuNo: '' }]
      },
      saleCity: {
        isAllChecked: false,
        isIndeterminate: false, // 设置 indeterminate 状态，只负责样式控制
        cityCodes: [], // 城市code集合
      },
      submitReason: {
        visible: false,
      },
      btnLoading: {
        submit: false
      },
      submitLoading: false,
      formData: {
        saleCityUuids: [],
        supplyUuid: ''
      },
      options: {
        saleCity: [],
        supplier: []
      },
      tableInfo: {
        columns: [],
        list: [],
        loading: false,
        mapList: new Map()
      },
      submitData: [], // 提交接口所需入参数据
      goodsLinked: {
        dimensionKeyList: ['uuid'], // 关联弹框维度key值列表 --- 以销售城市和sku为维度
        requestApi: {
          url: ['/sysback/supplyarea/getProductSupplyAreas'],
          type: 'post'
        },
        distinctParams: {
          notAssociated: 'uuidNotInSet',
          associated: 'uuidInSet'
        },
        columns: [
          {
            title: '供应商编码',
            key: 'supplyUuid',
          },
          {
            title: '供应商名称',
            key: 'supplyName',
          },
          {
            title: '商品名称',
            key: 'productName',
          },
          {
            title: '商品分类',
            key: 'categoryPath',
          },
          {
            title: 'SKU编码',
            key: 'skuNo'
          },
          {
            title: '区域',
            key: 'saleAreaName'
          },
          {
            title: '城市',
            key: 'saleCityName'
          },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
            fixed: 'right',
          }
        ]
      },
      apiObj: {
        getTableData: {
          url: '/sysback/supplyarea/getSupplyAreaInfoByUuids',
          type: 'post'
        },
        dataSubmit: {
          url: '/sysback/supplyarea/batchUpdateSupplyAreaInfo',
          type: 'post'
        },
        getExistInfo: { // 获取已有信息 by recordNo单据号
          url: '/sysback/product/update/record/getSupplyAreaInfoRecord',
          type: 'post'
        }
      }
    };
  },
  mounted () {
    this.setCanOpeState()
    this.loadInitDataInMounted();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    ...mapState('commonComps/batchMainSupplyAssociatedModal', [
      'associatedRowList'
    ])
  },
  methods: {
    ...mapMutations('commonComps/batchMainSupplyAssociatedModal', [
      'CHANGE_MODAL_SWITCH', 'CLEAR_GOODS'
    ]),
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // 选择城市groups为空
    isEmptyForSaleCityGroups () {
      return this.options.saleCity.length === 0;
    },
    // 当前集合为空,默认检测表格数据
    isEmptyForCurrentList (currentList = this.tableInfo.list) {
      return currentList.length === 0;
    },
    // 当前提交量超出限制
    isMoreThanLimitForSubmitAmount () {
      return this.tableInfo.list.length > BATCH_EDIT_MAINSUPPLY;
    },
    // 提交原因为空
    isEmptyForSubmitReason () {
      return !this.launchReason;
    },
    // 当前项是主供
    isMainSupplyForItem (item) {
      return item.isMainSupply === '1';
    },
    // 当前项不是主供
    isNotMainSupplyForItem (item) {
      return item.isMainSupply === '2';
    },
    // 相同的城市和sku编码
    isSameCityUuidAndSkuNo (row, item) {
      return (item.saleCityUuid === row.saleCityUuid) && (item.skuNo === row.skuNo);
    },
    // 没有勾选城市
    isEmptyByCheckedCity () {
      return this.formData.saleCityUuids.length === 0;
    },
    // 检索条件是否为空
    isEmptyForSearchCondition () {
      if (this.isEmptyByCheckedCity() && !this.formData.supplyUuid) {
        this.$message.warning('请选择检索条件');
        return true;
      }
      if (this.isEmptyByCheckedCity()) {
        this.$message.warning('检索条件：销售城市不能为空');
        return true;
      }
      if (!this.formData.supplyUuid) {
        this.$message.warning('检索条件：供应商不能为空');
        return true;
      }
      return false;
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      this.tableInfo.columns = getBatchModifyColumnsFn({
        selectMethods: this.handleChangeMainSupply
      });
      const { recordNo } = this.$route.query;
      if (recordNo) {
        this.getExistTableDataByRecordNo(recordNo);
      }
    },
    // 获取已有信息 by 单据号
    getExistTableDataByRecordNo (recordNo) {
      const { url, type } = this.apiObj.getExistInfo;
      this.postRequestTableData({ url: `${url}?recordNo=${recordNo}`, type }).then(retData => {
        if (retData) {
          this.tableInfo.list = retData.supplyAreaDTOS;
          this.footerFields = retData.recordDetail;
          this.launchReason = retData.launchReason; // 设置发起原因回显
          this.getAllOptionsForSearchForm(this.tableInfo.list);
        }
      })
    },
    // 获取reduce处理后的表格初始化数据
    getInitTableDataByReduced (retData) {
      return retData.reduce((value, item) => {
        item.isMainSupplyOld = item.isMainSupply;
        value.push(item);
        return value;
      }, []);
    },
    // 获取表格数据 by 高级关联
    getTableDataBySeniorLinked (skuNos) {
      this.CLEAR_GOODS(); // 高级关联获取数据，需要清空关联商品
      this.postRequestTableData({
        ...this.apiObj.getTableData,
        data: { skuNos }
      }).then(retData => {
        if (retData) {
          this.tableInfo.list = this.getInitTableDataByReduced(retData);
          this.getAllOptionsForSearchForm(this.tableInfo.list);
        }
      });
    },
    // 获取表格数据 by 关联商品
    getTableDataByGoodsLinked () {
      const uuids = getListByMapDimensionKey(this.associatedRowList);
      if (this.isEmptyForCurrentList(uuids)) {
        this.tableInfo.list = [];
        return false;
      }
      this.postRequestTableData({
        ...this.apiObj.getTableData, data: { uuids }
      }).then(retData => {
        if (retData) {
          this.tableInfo.list = this.getInitTableDataByReduced(retData);
          this.getAllOptionsForSearchForm(this.tableInfo.list);
        }
      });
    },
    // 根据数据源获取预处理集合的方法
    getPreDisposedMethodBySource (list) {
      return function ({ valueKey, labelKey, labelParentKey }) {
        let listByUuid = new Map();
        list.forEach(item => {
          listByUuid.set(item[valueKey], {
            value: item[valueKey],
            label: labelParentKey
              ? (item[labelParentKey] ? item[labelParentKey][labelKey] : '')
              : (item[labelKey])
          })
        });
        return getArraysByMaps(listByUuid)
      }
    },
    /* 获取options的方法 */
    getAllOptionsForSearchForm (dataSource) {
      let foo = this.getPreDisposedMethodBySource(dataSource);
      this.options.supplier = foo({
        valueKey: 'supplyUuid',
        labelKey: 'supplyName',
        labelParentKey: 'supplyInfoDTO'
      });
      this.options.saleCity = foo({
        valueKey: 'saleCityUuid',
        labelKey: 'saleCityName'
      });
      foo = null;
    },
    // 获取符合批量修改条件的集合
    getEligibleListByBatchModify () {
      const { saleCityUuids, supplyUuid } = this.formData;
      return this.tableInfo.list.filter(item => {
        if (saleCityUuids.includes(item.saleCityUuid) && item.supplyUuid === supplyUuid) {
          if (this.isNotMainSupplyForItem(item)) {
            this.handleChangeMainSupply({ row: item, val: '1' });
          }
          return item;
        }
      });
    },
    // 改变提交原因弹框的开启关闭状态
    updateVisibleForSubmitReasion (isOpen = false) {
      this.submitReason.visible = isOpen;
    },
    // 清空提交原因弹框的内容
    clearSubmitReasonText () {
      this.launchReason = '';
    },
    // 清空表单筛选条件
    clearFormData () {
      this.formData = {
        saleCityUuids: [],
        supplyUuid: ''
      }
    },
    // 清空全选状态
    clearStateForAllChecked () {
      this.saleCity.isAllChecked = false;
    },
    // 全选
    handleAllCheckedForSaleCity (isAllChecked) {
      const saleCityUuids = this.options.saleCity.map(item => item.value);
      this.formData.saleCityUuids = isAllChecked ? saleCityUuids : [];
      this.saleCity.isIndeterminate = false;
    },
    // 单选
    handleCheckedForSaleCity (list) {
      this.formData.saleCityUuids = list;
    },
    // 删除表格row
    handleDeleteTableRow ({ row }) {
      // SKU+城市 维度
      this.tableInfo.list = this.tableInfo.list.filter(
        item => (item.saleCityUuid + item.skuNo) !== (row.saleCityUuid + row.skuNo)
      );
      this.getAllOptionsForSearchForm(this.tableInfo.list);
    },
    // 批量删除-根据城市删除
    handleBatchDelete () {
      if (this.isEmptyByCheckedCity()) {
        return this.$message.warning('请选择城市后再进行批量删除');
      }
      this.tableInfo.list = this.tableInfo.list.filter(
        item => !this.formData.saleCityUuids.includes(item.saleCityUuid)
      )
      this.getAllOptionsForSearchForm(this.tableInfo.list);
      this.clearFormData();
      this.clearStateForAllChecked();
      this.$message.success('批量删除成功');
    },
    // 高级关联
    handleSeniorLinked () {
      sessionStorage.setItem('buttonId', getBtnsId('高级关联'));
      this.seniorLinked.visible = true;
    },
    // 关联商品
    handleGoodsLinked () {
      sessionStorage.setItem('buttonId', getBtnsId('关联商品'));
      this.CHANGE_MODAL_SWITCH(true);
    },
    handleChangeMainSupply ({ row, val }) {
      /* 产品需求：
       * 主供状态可以由否改为是，同时此销售城市销售的商品原来所对应的主供供应商就改为否
       */
      const supplyIndex = this.tableInfo.list.findIndex(
        item => this.isSameCityUuidAndSkuNo(row, item) && this.isMainSupplyForItem(item)
      )
      if (supplyIndex !== -1) {
        this.$set(this.tableInfo.list[supplyIndex], 'isMainSupply', '2');
      }
      row.isMainSupply = val;
      this.getAllOptionsForSearchForm(this.tableInfo.list);
    },
    // 批量修改
    handleBatchModify () {
      if (this.isEmptyForSearchCondition()) { return; };
      if (this.isEmptyForCurrentList(this.getEligibleListByBatchModify())) {
        return this.$message.warning('没有检索到符合条件的数据');
      }
      this.clearFormData();
      this.clearStateForAllChecked();
      return this.$message.success('修改成功');
    },
    // 取消-提交原因弹框
    handleCloseBySubmitReason () {
      this.clearSubmitReasonText();
      this.updateVisibleForSubmitReasion();
    },
    // 提交-表单提交
    handleSubmit () {
      if (this.isEmptyForCurrentList()) {
        return this.$message.warning('请先关联商品');
      }
      if (this.isMoreThanLimitForSubmitAmount()) {
        return this.$message.warning(`当前单据提交的行数不能超过${BATCH_EDIT_MAINSUPPLY}`)
      }
      this.submitData = this.tableInfo.list.filter(item => item.isMainSupply !== item.isMainSupplyOld);
      if (this.isEmptyForCurrentList(this.submitData)) {
        return this.$message.warning('数据未发生变动，不允许提交');
      }
      this.updateVisibleForSubmitReasion(true);
    },
    // 提交-提交原因弹框
    handleSubmitBySubmitReason () {
      if (this.isEmptyForSubmitReason()) {
        return this.$message.warning('请输入原因');
      }
      const { url, type } = this.apiObj.dataSubmit;
      this.postRequestSubmit({
        url,
        type,
        data: {
          supplyAreaDTOS: this.submitData,
          launchReason: this.launchReason // 发起原因字段
        }
      }).then(retStatus => {
        if (retStatus) {
          this.$message.success('提交成功');
          this.$router.push({ name: 'chageFromManageList' });
        }
      });
    },
    // 获取表格数据post请求-根据关联商品
    async postRequestTableData ({ url, type, data, isFormData = false }) {
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
        this.tableInfo.list = [];
      } catch (err) {
        this.tableInfo.list = [];
        this.tableInfo.loading = false;
      }
    },
    // 提交post请求
    async postRequestSubmit ({ url, type, data, isFormData = false }) {
      try {
        this.btnLoading.submit = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.btnLoading.submit = false;
        if (isResponseSuccessState(res.retStatus)) { return true; }
      } catch (err) { this.btnLoading.submit = false; }
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-card__header {
  padding: 10px 20px;
}
/deep/ .el-form-item {
  margin-bottom: 10px;
}
.city-list-wrap {
  padding-left: 80px;
}
</style>
